package com.mrwang.service;

import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@Service
public class UploadService {
    @Resource
    FastFileStorageClient fastFileStorageClient;
    @Value("${imagesUrl}")
    String baseUrl;

    public static final List<String> CONTENT_TYPES= Arrays.asList("image/jpeg","image/png","image/jpg","image/gif");

    private static final Logger logger= LoggerFactory.getLogger(UploadService.class);

    public String upload(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();

        String contentType = file.getContentType();
        if (!CONTENT_TYPES.contains(contentType)){
            logger.info("文件类型不合法:{}",originalFilename);
            return null;
        }
        try {
             BufferedImage bufferedImage= ImageIO.read(file.getInputStream());
             if (bufferedImage==null){
                 logger.info("文件内容不合法:{}",originalFilename);
                 return null;
             }
             /*file.transferTo(new File("C:/Users/Lenovo/Desktop/images/"+originalFilename));*/
            String ext = StringUtils.substringAfterLast(originalFilename, ".");
            StorePath storePath = fastFileStorageClient.uploadFile(file.getInputStream(), file.getSize(), ext, null);

            return baseUrl+storePath.getFullPath();
        }catch (IOException e){
            logger.info("服务器内部错误:{}",originalFilename);
            e.printStackTrace();
        }
        return null;
    }
}
